package com.whu.exp1jsp.controller;

import com.whu.exp1jsp.dao.ProductDAO;
import com.whu.exp1jsp.dao.PurchaseDAO;
import com.whu.exp1jsp.pojo.ProductSt;
import com.whu.exp1jsp.pojo.UserSt;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "updateProductServlet", value = "/updateProduct-servlet")
public class UpdateProductServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setAttribute("mode", 1);

        HttpSession session = request.getSession();

        Long productId = Long.parseLong(request.getParameter("productId"));
        String productTitle = new String(request.getParameter("productTitle").getBytes("ISO-8859-1"), "UTF-8") ;
        double productPrice = Double.parseDouble(request.getParameter("productPrice"));
        String location = new String(request.getParameter("location").getBytes("ISO-8859-1"), "UTF-8");
        String productIntro = new String(request.getParameter("productIntro").getBytes("ISO-8859-1"), "UTF-8");

        if(productId == null){
            request.setAttribute("errorMessage", "商品不存在");
            request.getRequestDispatcher("index.jsp").forward(request, response);
            return;
        }

        UserSt user = session.getAttribute("user") == null ? null : (UserSt) session.getAttribute("user");
        if (user == null){
            request.setAttribute("error", "请先登录");
            request.getRequestDispatcher("login.jsp").forward(request, response);
            return;
        }

        //获取商品
        ProductSt productSt = null;
        ProductDAO productDAO = new ProductDAO();
        try {
            productSt = productDAO.selectProductById(productId);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        //更新商品
        assert productSt != null;
        productSt.setProductPrice(productPrice);
        productSt.setProductIntro(productIntro);
        productSt.setProductTitle(productTitle);
        productSt.setLocation(location);
        try {
            productDAO.updateProduct(productSt);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        request.setAttribute("successMessage", "更新成功");
        request.getRequestDispatcher("my-servlet").forward(request, response);

    }
}
